package com.shelpe.services.lexicon.service.filter;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.shelpe.services.lexicon.constants.Device;
import com.shelpe.services.lexicon.entity.AdgroupRecord;
import com.shelpe.services.lexicon.entity.KeywordRecommend;
import com.shelpe.services.lexicon.po.Adgroup;
import com.shelpe.services.lexicon.repository.jpa.AdgroupRepository;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class MatchingKeywordFilter implements KeywordRecommendsFilter {

	@Autowired
	private AdgroupRepository adgroupRepository;
	
	@Override
	public List<KeywordRecommend> run(List<KeywordRecommend> recommends, AdgroupRecord record, Device device) {
		Adgroup adgroup = this.adgroupRepository.findOne(record.getAdgroupID());
		if(adgroup == null || StringUtils.isBlank(adgroup.getProductAttributes())){
			return recommends;
		}
		int titleScore = this.match(adgroup.getProductName(), ",");
		int attrScore = this.match(adgroup.getProductAttributes(), "");
		if(titleScore > 0 || attrScore > 0){
			return recommends;
		}
		
		List<KeywordRecommend> remainings = new ArrayList<KeywordRecommend>(recommends.size() * 2);
		
		for(KeywordRecommend recommend: recommends){
			boolean support = true;
			
			if(this.match(recommend.getWord(), ",") > 0){
				log.debug("{} is removed by filter", recommend.getWord());
				support  = false;
			}
			
			if(support){
				remainings.add(recommend);
			}
		}
		
		return remainings;
	}


	private int match(String word , String split){
		int index = 0;
		
		String[] matchings = this.matchings();
		for(String matching:matchings){
			index++;
			if(word.contains(split + matching + split)){
				break;
			}
		}
		
		return index;
	}
	
	
	protected abstract String[] matchings();

}
